/*
 * Created by VisualGDB. Based on hello-jni example.
 * Copyright (C) 2009 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.ykit.ctp.yone;

import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.egl.EGLContext;
import javax.microedition.khronos.egl.EGLDisplay;
import javax.microedition.khronos.opengles.GL10;

import android.media.MediaPlayer;
import android.net.http.SslError;
import android.os.Bundle;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.PixelFormat;
import android.graphics.drawable.GradientDrawable;
import android.opengl.GLSurfaceView;
import android.text.InputType;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.telephony.TelephonyManager;
import android.widget.Toast;

import java.io.IOException;

import io.rong.imlib.AnnotationNotFoundException;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message;
import io.rong.message.CommandNotificationMessage;
import io.rong.message.ContactNotificationMessage;
import io.rong.message.GroupNotificationMessage;
import io.rong.message.ImageMessage;
import io.rong.message.InformationNotificationMessage;
import io.rong.message.ProfileNotificationMessage;
import io.rong.message.TextMessage;
import io.rong.message.VoiceMessage;

public class yoneActivity extends Activity {
    static String TAG = ">Fuel4D<";
    static FrameLayout mFrameLayout = null;
    static Fuel4DView mGameView = null;
    static Fuel4DEdit mEditBox = null;
    static LinearLayout mWebLayout = null;
    static LinearLayout mWebBar = null;
    static Button mWebClose = null;
    static TextView mWebTitle = null;
    static Button mWebBack = null;
    static ProgressBar mWebProgress = null;
    static WebView mWebView = null;
    static AssetManager mAssetMgr = null;
    static InputMethodManager mImmMethodMgr = null;
    static int mImmMethodV1 = 0;
    static int mImmMethodV2 = 0;
    static yoneActivity uiInstance;
    public static String mUserId;
    public static RongIMClient mRongIMClient;

    @Override protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        uiInstance = this;
        Log.i(TAG, ">>FGE>> Activity Create ...");

        mImmMethodMgr = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
        mAssetMgr = getAssets();

        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE | WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        InitView();

        setContentView(mFrameLayout);

        mGameView.setVisibility(View.VISIBLE);
        mGameView.requestFocus();

        Log.i(TAG, ">>FGE>> Apk Paths：" + getPackageResourcePath().toString());
        Log.i(TAG, ">>FGE>> Apk Files：" + getFilesDir().toString());
        Log.i(TAG, ">>FGE>> Apk Cache：" + getCacheDir().toString());
        toNativeAppCreate(mAssetMgr, getPackageResourcePath().toString(), getFilesDir().toString(), getCacheDir().toString());

		//IMEI
		TelephonyManager tm = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
		String imei = tm.getDeviceId();
		toNativeAppIMEI(imei);
		//toNativeAppInitRongLib();	//init rongcloud
        Log.i(TAG, ">>FGE>> Activity Create > OK <");

        RongIMClient.init(this);

    }

    public void registerReceiveMessageListener() {

        RongIMClient.setOnReceiveMessageListener(onReceiveMessageListener);
    }

    RongIMClient.OnReceiveMessageListener onReceiveMessageListener = new RongIMClient.OnReceiveMessageListener() {

        @Override
        public boolean onReceived(Message message, int left) {

            Log.e("------", "0605--------onReceived--------------------");


            if (message.getContent() instanceof TextMessage) {
                TextMessage textMessage = (TextMessage) message.getContent();

                Log.d("onReceived", "TextMessage---收收收收--接收到一条【文字消息】-----" + textMessage.getContent() + ",getExtra:" + textMessage.getExtra());

            } else if (message.getContent() instanceof ImageMessage) {

                final ImageMessage imageMessage = (ImageMessage) message.getContent();
                Log.d("onReceived", "ImageMessage--收收收收--接收到一条【图片消息】---ThumUri--" + imageMessage.getLocalUri());
                Log.d("onReceived", "ImageMessage--收收收收--接收到一条【图片消息】----Uri--" + imageMessage.getRemoteUri());

                new Thread(new Runnable() {
                    @Override
                    public void run() {

                        RongIMClient.getInstance().downloadMedia(Conversation.ConversationType.PRIVATE, mUserId, RongIMClient.MediaType.IMAGE, imageMessage.getRemoteUri().toString(), new RongIMClient.DownloadMediaCallback() {

                            @Override
                            public void onProgress(int i) {
                                Log.d("downloadMedia", "onProgress:" + i);
                            }

                            @Override
                            public void onSuccess(String s) {
                                Log.d("downloadMedia", "onSuccess:" + s);
                            }

                            @Override
                            public void onError(RongIMClient.ErrorCode errorCode) {
                                Log.d("downloadMedia", "onError:" + errorCode.getValue());
                            }
                        });
                    }
                }).start();

            } else if (message.getContent() instanceof VoiceMessage) {

                final VoiceMessage voiceMessage = (VoiceMessage) message.getContent();

//                Log.d("onReceived", "VoiceMessage--收收收收--接收到一条【语音消息】-----" + voiceMessage.getUri());
                Log.e("onReceived", "VoiceMessage--收收收收--接收到一条【语音消息】 voiceMessage.getExtra-----" + voiceMessage.getExtra());

                new Thread(new Runnable() {

                    @Override
                    public void run() {

                        MediaPlayer mMediaPlayer = new MediaPlayer();
                        mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {

                            @Override
                            public void onPrepared(MediaPlayer mp) {
                                mp.start();
                            }
                        });

                        try {
                            mMediaPlayer.setDataSource(uiInstance, voiceMessage.getUri());
                            mMediaPlayer.prepare();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            } else if (message.getContent() instanceof GroupNotificationMessage) {

                GroupNotificationMessage groupInvitationNotification = (GroupNotificationMessage) message.getContent();

                Log.d("onReceived", "GroupInvitationNotification--收收收收--接收到一条【群组邀请消息】-----" + groupInvitationNotification.getMessage());

            } else if (message.getContent() instanceof ContactNotificationMessage) {
                ContactNotificationMessage mContactNotificationMessage = (ContactNotificationMessage) message.getContent();
                Log.d("onReceived", "mContactNotificationMessage--收收收收--接收到一条【联系人（好友）操作通知消息】-----" + mContactNotificationMessage.getMessage() + ",getExtra:" + mContactNotificationMessage.getExtra());

            } else if (message.getContent() instanceof ProfileNotificationMessage) {
                ProfileNotificationMessage mProfileNotificationMessage = (ProfileNotificationMessage) message.getContent();
                Log.d("onReceived", "GroupNotificationMessage--收收收收--接收到一条【资料变更通知消息】-----" + mProfileNotificationMessage.getData() + ",getExtra:" + mProfileNotificationMessage.getExtra());

            } else if (message.getContent() instanceof CommandNotificationMessage) {
                CommandNotificationMessage mCommandNotificationMessage = (CommandNotificationMessage) message.getContent();
                Log.d("onReceived", "GroupNotificationMessage--收收收收--接收到一条【命令通知消息】-----" + mCommandNotificationMessage.getData() + ",getName:" + mCommandNotificationMessage.getName());
            } else if (message.getContent() instanceof InformationNotificationMessage) {
                InformationNotificationMessage mInformationNotificationMessage = (InformationNotificationMessage) message.getContent();
                Log.d("onReceived", "InformationNotificationMessage--收收收收--接收到一条【小灰条消息】-----" + mInformationNotificationMessage.getMessage() + ",getName:" + mInformationNotificationMessage.getExtra());

            }/*else if (message.getContent() instanceof AgreedFriendRequestMessage) {
                AgreedFriendRequestMessage mAgreedFriendRequestMessage = (AgreedFriendRequestMessage) message.getContent();
                Log.d("onReceived", "AgreedFriendRequestMessage--收收收收--接收到一条【加好友消息】-----" + mAgreedFriendRequestMessage.getMessage() );

            }*/
            return false;
        }

    };

    private void InitView()
    {
        int drawColor = 0xffe0e0e0;
        GradientDrawable drawClose = new GradientDrawable();
        drawClose.setShape(GradientDrawable.RECTANGLE);
        drawClose.setStroke(3, drawColor);
        drawClose.setColor(0xff0084e0);
        float drawCloseTB[] = {24,24, 0,0, 0,0, 24,24};
        drawClose.setCornerRadii(drawCloseTB);

        GradientDrawable drawBack = new GradientDrawable();
        drawBack.setShape(GradientDrawable.RECTANGLE);
        drawBack.setStroke(3, drawColor);
        drawBack.setColor(0xff0084e0);
        float drawBackTB[] = {0,0, 24,24, 24,24, 0,0};
        drawBack.setCornerRadii(drawBackTB);

        int layout_match = FrameLayout.LayoutParams.MATCH_PARENT;
        int layout_wrap_ = FrameLayout.LayoutParams.WRAP_CONTENT;

        mFrameLayout = new FrameLayout(this);
        mFrameLayout.setLayoutParams(new FrameLayout.LayoutParams(layout_match, layout_match));

        mGameView = new Fuel4DView(getApplication());
        mGameView.setLayoutParams(new FrameLayout.LayoutParams(layout_match, layout_match));
        mFrameLayout.addView(mGameView);

        mEditBox = new Fuel4DEdit(this);
        mEditBox.setLayoutParams(new FrameLayout.LayoutParams(layout_match, layout_wrap_));
        mEditBox.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI);
        mEditBox.setVisibility(View.INVISIBLE);
        mFrameLayout.addView(mEditBox);

        mWebLayout = new LinearLayout(this);
        mWebLayout.setLayoutParams(new FrameLayout.LayoutParams(layout_match, layout_match));
        mWebLayout.setOrientation(LinearLayout.VERTICAL);
        mWebLayout.setVisibility(View.INVISIBLE);
        mFrameLayout.addView(mWebLayout);

        mWebBar = new LinearLayout(this);
        mWebBar.setLayoutParams(new LinearLayout.LayoutParams(layout_match, layout_wrap_));
        mWebBar.setBackgroundColor(0xffffffff);
        mWebLayout.addView(mWebBar);

        mWebClose = new Button(this);
        mWebClose.setLayoutParams(new LinearLayout.LayoutParams(layout_wrap_, layout_match));
        mWebClose.setText("关闭页面");
        mWebClose.setBackgroundDrawable(drawClose);
        mWebClose.setTextColor(drawColor);
        mWebBar.addView(mWebClose);

        mWebBack = new Button(this);
        mWebBack.setLayoutParams(new LinearLayout.LayoutParams(layout_wrap_, layout_match));
        mWebBack.setText("回上一页");
        mWebBack.setBackgroundDrawable(drawBack);
        mWebBack.setTextColor(drawColor);
        mWebBar.addView(mWebBack);

        LinearLayout.LayoutParams lpTitle = new LinearLayout.LayoutParams(layout_match, layout_match);
        lpTitle.weight = 0.8f;
        mWebTitle = new TextView(this);
        mWebTitle.setLayoutParams(lpTitle);
        mWebTitle.setText("网页标题");
        mWebTitle.setBackgroundColor(drawColor);
        mWebTitle.setTextColor(0xff406080);
        mWebTitle.setGravity(Gravity.CENTER);
        mWebBar.addView(mWebTitle, 1);

        mWebProgress = new ProgressBar(this);
        mWebProgress.setLayoutParams(new LinearLayout.LayoutParams(layout_match, 100));
        mWebProgress.setMax(100);
        mWebProgress.setVisibility(View.GONE);
        mWebLayout.addView(mWebProgress);

        mWebView = new WebView(this);
        mWebView.setLayoutParams(new LinearLayout.LayoutParams(layout_match, layout_match));
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebLayout.addView(mWebView);

        mEditBox.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    toNativeEventInputResult(mImmMethodV1, mImmMethodV2, v.getText().toString());
                    fromNativeInputClose();
                }
                return false;
            }
        });
        mWebView.setWebViewClient(new WebViewClient() {
            @Override public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                mWebProgress.setProgress(1);
                mWebProgress.setVisibility(View.VISIBLE);
                toNativeEventWebJump(url);
                return true;
            }
            @Override public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
            }
            @Override public void onPageFinished(WebView view,String url) {
                mWebProgress.setVisibility(View.GONE);
            }
        });
        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override public void onReceivedTitle(WebView view, String title) {
                mWebTitle.setText(title);
            }
            @Override public void onProgressChanged(WebView view, int newProgress) {
                mWebProgress.setProgress(newProgress);
            }
        });
        mWebView.setOnKeyListener(new View.OnKeyListener(){
            @Override public boolean onKey(View v, int keyCode, KeyEvent event) {
                if ((keyCode == KeyEvent.KEYCODE_BACK)) {
                    if (mWebView.canGoBack())
                        mWebView.goBack();
                    else
                        fromNativeWebClose();
                    return true;
                }
                return false;
            }
        });
        mWebClose.setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v) {
                fromNativeWebClose();
            }
        });
        mWebBack.setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v) {
                if (mWebView.canGoBack())
                    mWebView.goBack();
            }
        });
    }
    @Override protected void onPause() {
        Log.i(TAG, ">>FGE>> Activity Pause");
        toNativeAppPause();
        super.onPause();
        mGameView.onPause();
    }
    @Override protected void onResume() {
        Log.i(TAG, ">>FGE>> Activity Resume");
        super.onResume();
        mGameView.onResume();
        toNativeAppResume();
    }
    @Override protected void onDestroy() {
        Log.i(TAG, ">>FGE>> Activity Destroy");
        toNativeAppDestroy();
        super.onDestroy();

        System.exit(0);
        android.os.Process.killProcess(android.os.Process.myPid());
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        manager.killBackgroundProcesses(getPackageName());
    }
    @Override public boolean onTouchEvent(final MotionEvent pMotionEvent) {
        final int ptCount = pMotionEvent.getPointerCount();
        int type = pMotionEvent.getAction() & MotionEvent.ACTION_MASK;
        if (mEditBox.getVisibility() == View.VISIBLE) {
            if (type == MotionEvent.ACTION_UP)
                fromNativeInputClose();
            return true;
        }
        if (mWebLayout.getVisibility() == View.VISIBLE)
            return true;
        if (ptCount > 0) {
            switch (type) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_MOVE:
                toNativeEventCursor(type, pMotionEvent.getX(0), pMotionEvent.getY(0));
                break;
            }
        }
        return true;
    }
    @Override public boolean onKeyDown(final int pKeyCode, final KeyEvent pKeyEvent) {
        if (toNativeEventKey(pKeyEvent.getAction(), pKeyCode))
            return true;
        return super.onKeyDown(pKeyCode, pKeyEvent);
    }
    @Override public boolean onKeyUp(final int pKeyCode, final KeyEvent pKeyEvent) {
        if (toNativeEventKey(pKeyEvent.getAction(), pKeyCode))
            return true;
        return super.onKeyUp(pKeyCode, pKeyEvent);
    }

    static {
        System.loadLibrary("FuelCore");
        System.loadLibrary("FuelEngine");
        System.loadLibrary("FuelUI");
        System.loadLibrary("thostmduserapi");
        System.loadLibrary("thostmduserapi_wrap");
        System.loadLibrary("yone");
    }

    public static native void    toNativeAppCreate(AssetManager asset_mgr, String apk_path, String apk_files, String apk_cache);
    public static native void    toNativeAppDestroy();
    public static native void    toNativeAppPause();
    public static native void    toNativeAppResume();
    public static native void    toNativeDevCreate();
    public static native void    toNativeDevRun();
    public static native void    toNativeDevLost();
    public static native void    toNativeDevReset(int width, int height);
    public static native boolean toNativeEventCursor(int type, float x, float y);
    public static native boolean toNativeEventKey(int type, int key);
    public static native void    toNativeEventInputResult(int id1, int id2, String vl);
    public static native void    toNativeEventWebJump(String url);
    public static native void    toNativeAppIMEI(String imei);
    //public static native void    toNativeAppInitRongLib();

    public static void fromNativeInputOpen(String default_txt, boolean multi_line, int mode, int id1, int id2) {
        Log.i(TAG, ">>FGE>> Android 打开输入法（" + default_txt + "）");
        int input_flag = 0;
        switch (mode) {
        case 1: input_flag |= InputType.TYPE_CLASS_NUMBER; break;
        case 2: input_flag |= InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD; break;
        case 3: input_flag |= InputType.TYPE_CLASS_NUMBER | InputType.TYPE_TEXT_VARIATION_PASSWORD; break;
        case 4: input_flag |= InputType.TYPE_CLASS_PHONE; break;
        default: input_flag |= InputType.TYPE_CLASS_TEXT;
            if (multi_line)
                input_flag = InputType.TYPE_TEXT_FLAG_MULTI_LINE | InputType.TYPE_TEXT_FLAG_IME_MULTI_LINE;
        }
        mEditBox.setVisibility(View.VISIBLE);
        mEditBox.setInputType(input_flag);
        mEditBox.setText(default_txt);
        mEditBox.setSelection(mEditBox.getText().length());
        mEditBox.requestFocus();
        mImmMethodV1 = id1;
        mImmMethodV2 = id2;
        mImmMethodMgr.showSoftInput(mEditBox, 0);
    }
    public static void fromNativeInputClose() {
        Log.i(TAG, ">>FGE>> Android 关闭输入法");
        mImmMethodMgr.hideSoftInputFromWindow(mGameView.getWindowToken(), 0);
        mEditBox.setVisibility(View.INVISIBLE);
        mGameView.requestFocus();
    }
    public static void fromNativeWebOpen(String url) {
        Log.i(TAG, ">>FGE>> Android 显示网页（" + url + "）");
        mWebLayout.setVisibility(View.VISIBLE);
        mWebView.requestFocus();
        mWebView.loadUrl(url);
        mWebProgress.setProgress(1);
        mWebProgress.setVisibility(View.VISIBLE);
    }
    public static void fromNativeWebClose() {
        Log.i(TAG, ">>FGE>> Android 关闭网页");
        mWebView.stopLoading();
        mWebLayout.setVisibility(View.INVISIBLE);
        mGameView.requestFocus();
    }

    public static void fromNativeRongCloud(String token)
    {
        try
        {
       // RongIMClient.init(Context);
        mRongIMClient = RongIMClient.connect(token, new RongIMClient.ConnectCallback() {
            @Override
            public void onTokenIncorrect() {
                Log.e(TAG, "--connect--onTokenIncorrect-------");
            }

            @Override
            public void onSuccess(String userId) {
                Log.e(TAG, "--connect--onSuccess----userId---" + userId);
                mUserId = userId;
                uiInstance.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(uiInstance, "连接成功！", Toast.LENGTH_LONG).show();
                        try {
                            RongIMClient.registerMessageType(ContactNotificationMessage.class);

                        } catch (AnnotationNotFoundException e) {
                            e.printStackTrace();
                        }
//                        connectButton.setText("连接服务器成功!");

                    }
                });
            }

            @Override
            public void onError(RongIMClient.ErrorCode errorCode) {
                Log.e(TAG, "--connect--errorCode-------" + errorCode);
                uiInstance.runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        Toast.makeText(uiInstance, "连接失败！", Toast.LENGTH_LONG).show();
                    }
                });
            }
        });

        uiInstance.registerReceiveMessageListener();

    } catch (Exception e) {
        e.printStackTrace();
    }
    }
}

class Fuel4DView extends GLSurfaceView {
    public Fuel4DView(Context context) {
        super(context);
        init(false, 0, 0);
    }
    public Fuel4DView(Context context, boolean translucent, int depth, int stencil) {
        super(context);
        init(translucent, depth, stencil);
    }
    private void init(boolean translucent, int depth, int stencil) {
        if (translucent)
            this.getHolder().setFormat(PixelFormat.TRANSLUCENT);
        setEGLContextFactory(new ContextFactory());
        setEGLConfigChooser( translucent ?
            new ConfigChooser(8, 8, 8, 8, depth, stencil):
        new ConfigChooser(5, 6, 5, 0, depth, stencil) );
        setRenderer(new Renderer());
    }
    private static class ContextFactory implements GLSurfaceView.EGLContextFactory {
        private static int EGL_CONTEXT_CLIENT_VERSION = 0x3098;
        public EGLContext createContext(EGL10 egl, EGLDisplay display, EGLConfig eglConfig) {
            Log.i(yoneActivity.TAG, ">>FGE>> OpenGL ES Create Context ...");
            int[] attrib_list = {EGL_CONTEXT_CLIENT_VERSION, 2, EGL10.EGL_NONE};
            EGLContext context = egl.eglCreateContext(display, eglConfig, EGL10.EGL_NO_CONTEXT, attrib_list);
            return context;
        }
        public void destroyContext(EGL10 egl, EGLDisplay display, EGLContext context) {
            Log.i(yoneActivity.TAG, ">>FGE>> OpenGL ES Destroy Context ...");
            yoneActivity.toNativeDevLost();
            egl.eglDestroyContext(display, context);
        }
    }
    private static class ConfigChooser implements GLSurfaceView.EGLConfigChooser {
        public ConfigChooser(int r, int g, int b, int a, int depth, int stencil) {
            mRedSize = r;
            mGreenSize = g;
            mBlueSize = b;
            mAlphaSize = a;
            mDepthSize = depth;
            mStencilSize = stencil;
        }

        private static int EGL_OPENGL_ES2_BIT = 4;
        private static int[] s_configAttribs2 =
        {
            EGL10.EGL_RED_SIZE, 4,
            EGL10.EGL_GREEN_SIZE, 4,
            EGL10.EGL_BLUE_SIZE, 4,
            EGL10.EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
            EGL10.EGL_NONE
        };

        public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display) {
            int[] num_config = new int[1];
            egl.eglChooseConfig(display, s_configAttribs2, null, 0, num_config);
            int numConfigs = num_config[0];
            if (numConfigs <= 0)
                throw new IllegalArgumentException("No configs match configSpec");
            EGLConfig[] configs = new EGLConfig[numConfigs];
            egl.eglChooseConfig(display, s_configAttribs2, configs, numConfigs, num_config);
            return chooseConfig(egl, display, configs);
        }
        public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display, EGLConfig[] configs) {
            for(EGLConfig config : configs) {
                int d = findConfigAttrib(egl, display, config, EGL10.EGL_DEPTH_SIZE, 0);
                int s = findConfigAttrib(egl, display, config, EGL10.EGL_STENCIL_SIZE, 0);
                if (d < mDepthSize || s < mStencilSize)
                    continue;
                int r = findConfigAttrib(egl, display, config, EGL10.EGL_RED_SIZE, 0);
                int g = findConfigAttrib(egl, display, config, EGL10.EGL_GREEN_SIZE, 0);
                int b = findConfigAttrib(egl, display, config, EGL10.EGL_BLUE_SIZE, 0);
                int a = findConfigAttrib(egl, display, config, EGL10.EGL_ALPHA_SIZE, 0);
                if (r == mRedSize && g == mGreenSize && b == mBlueSize && a == mAlphaSize)
                    return config;
            }
            return null;
        }
        private int findConfigAttrib(EGL10 egl, EGLDisplay display, EGLConfig config, int attribute, int defaultValue) {
            if (egl.eglGetConfigAttrib(display, config, attribute, mValue))
                return mValue[0];
            return defaultValue;
        }

        protected int mRedSize;
        protected int mGreenSize;
        protected int mBlueSize;
        protected int mAlphaSize;
        protected int mDepthSize;
        protected int mStencilSize;
        private int[] mValue = new int[1];
    }
    private static class Renderer implements GLSurfaceView.Renderer {
        public void onDrawFrame(GL10 gl) {
            yoneActivity.toNativeDevRun();
        }
        public void onSurfaceChanged(GL10 gl, int width, int height) {
            Log.i(yoneActivity.TAG, ">>FGE>> OpenGL ES Surface Changed：" + width + " x " + height);
            yoneActivity.toNativeDevReset(width, height);
        }
        public void onSurfaceCreated(GL10 gl, EGLConfig config) {
            Log.i(yoneActivity.TAG, ">>FGE>> OpenGL ES Surface Created");
            yoneActivity.toNativeDevCreate();
        }
    }
}

class Fuel4DEdit extends EditText {
    public Fuel4DEdit(Context context) {
        super(context);
    } 
    @Override public boolean dispatchKeyEventPreIme(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            yoneActivity.fromNativeInputClose();
            return true;
        }
        return super.dispatchKeyEventPreIme(event);
    }
}
